//
//  CompseViewController.swift
//  GZWeibo
//
//  Created by Apple on 15/9/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class CompseViewController: UIViewController {

    /// 键盘控制器
    private lazy var keyboardViewController: EmoticonViewController = EmoticonViewController { [weak self] (emoticon) -> () in
//        print(emoticon)
        
        self?.textView.insertEmoticon(emoticon)
    }
    
    // MARK: - 监听方法
    /// 切换表情键盘
    @objc private func selectEmoticon() {
        // 系统默认键盘是 nil
        print(textView.inputView)
        
        // 退出键盘
        textView.resignFirstResponder()
        
        // 切换键盘
        textView.inputView = textView.inputView == nil ? keyboardViewController.view : nil
        
        // 激活键盘
        textView.becomeFirstResponder()
    }
    
    @objc private func close() {
        // 退掉键盘
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发布微博
    @objc private func sendStatus() {
        print("发布微博")
        
        // 1. 获取微博文本
        let text = textView.emoticonText
        
        // 2. 发布微博
        SVProgressHUD.show()
        NetworkTools.sharedTools.postStatus(text, image: selectPictureViewContoller.pictures.last) { (result, error) -> () in
            
            if error != nil {
                // 一旦调用了 dismiss，showInfo 不会显示
                SVProgressHUD.showInfoWithStatus("您的网络不给力!")
                return
            }
            SVProgressHUD.dismiss()
            
            print(result)
            self.close()
        }
    }
    
    /// 选择照片
    @objc private func selectPhoto() {
        print("选择照片")
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        // `重建`照片视图的约束 - 首先删除之前创建的所有约束，重建需要重新建立所有的约束
//        NSLayoutConstraint(item: "控件", attribute: "属性", relatedBy: "关系", toItem: "参照控件", attribute: "参照属性", multiplier: "乘积", constant: "约束")
//        NSLayoutConstraint(item: "控件", attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: "高度")
        /*
            make.bottom.equalTo(view.snp_bottom)
                 属性    关系     参照控件  参照属性
        
            * update 的时候要保证约束的 `参照控件` `参照属性` 一致
            * remake 的条件，约束参照对象发生改变
        
            提示：在使用自动布局时，最好不要频繁 remake 约束
        */
        
        // 判断约束是否已经重建
        if selectPictureViewContoller.view.frame.height > 0 {
            return
        }
        
        selectPictureViewContoller.view.snp_remakeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            // 建议不要写太固定的数值！
            make.height.equalTo(view.snp_height).multipliedBy(0.6)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(selectPictureViewContoller.view.snp_top)
        }
    }
    
    // MARK: - 键盘处理
    /// 监听键盘变化
    @objc private func keyboardChanged(n: NSNotification) {
        print(n)
        // 从 userInfo 中获取 endFrame
        // OC 中结构体保存在 字典 是 NSValue，基本数据类型是 NSNubmer
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 获取时间
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 动画曲线
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        // 更新 toolbar 的约束
        let screenHeight = UIScreen.mainScreen().bounds.height
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-screenHeight + rect.origin.y)
        }
        
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            // 设置动画曲线 `7` 苹果没有提供任何文档！
            // 如果给图层指定了多个动画，使用 curve 7 会取消之前的动画，直接从当前位置，运动到最后一个动画的指定位置
            // 注意：一旦使用 7 的动画曲线，动画时长无效！动画时长会变成 `0.5s`
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
        // 测试toolbar的动画时长 － 苹果的动画的 key 都是 keyPath
        let anim = toolbar.layer.animationForKey("position")
        print("toolbar 的动画时长是 \(anim?.duration)")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 如果照片选择视图已经显示，就不再激活键盘
        if selectPictureViewContoller.view.frame.height == 0 {
            textView.becomeFirstResponder()
        }
    }
    
    // MARK: - 搭建界面
    override func loadView() {
        view = UIView()
        
        // 设置背景颜色 － 默认背景颜色是 nil，会影响到`动画`的效率
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNavigation()
        prepareToolbar()
        prepareTextview()
        preparePictureView()
    }
    
    /// 准备照片选择控制器
    private func preparePictureView() {
        // 0. 添加子控制器
        addChildViewController(selectPictureViewContoller)
        
        // 1. 添加控制器视图
        view.insertSubview(selectPictureViewContoller.view, belowSubview: toolbar)
        
        // 2. 自动布局
        selectPictureViewContoller.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            // 初始高度为0，默认不显示
            make.height.equalTo(0)
        }
    }
    
    /// 准备文本视图
    private func prepareTextview() {
        view.addSubview(textView)
        
        // 设置成 None 就无法实现导航控制器的穿透！
        edgesForExtendedLayout = .None
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        
        // 添加占位标签 － 要添加到 textView 保证一起滚动！
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    /// 准备工具栏
    private func prepareToolbar() {
        // 1. 添加 tool bar
        view.addSubview(toolbar)
        // 咨询平面设计师
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 2. 自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }

        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "selectPhoto"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {

            let item = UIBarButtonItem(imageName: dict["imageName"]!,
                target: self,
                action: dict["actionName"])
            
            items.append(item)
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        
    }
    
    /// 准备导航栏
    private func prepareNavigation() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendStatus")
        
        // 禁用按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        // 如果一个控件点击不到会怎样！如果控件所在位置超出父视图范围，无法点击！
        // titleView.clipsToBounds = true
        
        // 1> 标题标签
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        titleView.addSubview(titleLabel)
        // 2> 姓名标签
        let name = UserAccountViewModel.sharedAccountViewModel.userAccount?.screen_name ?? ""
        let nameLabel = UILabel(title: name, color: UIColor.lightGrayColor(), fontSize: 13)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        navigationItem.titleView = titleView
    }
    
    // MARK: - 懒加载控件
    /// 选择照片控制器
    private lazy var selectPictureViewContoller = SelectPictureViewController()
    /// 工具条
    private lazy var toolbar = UIToolbar()
    /// 文本视图 － Swift 中，懒加载应该负责当前控件的创建和初始属性设置
    /// 至于添加控件这些代码，放在外面，因为没有智能提示！
    private lazy var textView: UITextView = {
        let tv = UITextView()
        
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        
        // 允许垂直拖拽
        tv.alwaysBounceVertical = true
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.delegate = self
        
        return tv
    }()
    /// 占位文本
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...",
        color: UIColor.lightGrayColor(),
        fontSize: 18)
}

// MARK: - UITextViewDelegate
extension CompseViewController: UITextViewDelegate {
    
    // 如果输入的是表情符号，默认不会执行此代理方法
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
